<template>
  <div>
    <el-form :inline="true" :model="query" class="demo-form-inline">
      <el-form-item label="关键字">
        <el-input v-model="query.keyword" placeholder="关键字"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="initPageData">查询</el-button>
        <el-button type="primary" icon="el-icon-delete" @click="batchDelete"  size="medium">批量删除</el-button>
        <el-button type="primary" icon="el-icon-plus" @click="showModal"  size="medium">新增</el-button>
      </el-form-item>
    </el-form>
  <el-table
    :data="kq.data"
    border
    style="width: 100%"
    stripe
    @selection-change="handleSelectionChange">
    <el-table-column
      type="selection"
      width="55">
    </el-table-column>
    <el-table-column
      prop="id"
      label="ID"
      width="100">
    </el-table-column>
    <el-table-column
      prop="name"
      label="部门"
      width="100">
    </el-table-column>
    <el-table-column
      prop="intro"
      label="部门介绍"
      width="100">
    </el-table-column>
    <el-table-column
        prop="create_time"
        label="创建时间"
        width="100">
    </el-table-column>
    <el-table-column
        prop="update_time"
        label="修改时间"
        width="100">
    </el-table-column>
    <el-table-column
      prop="head.username"
      label="领导"
      width="100">
    </el-table-column>
    <el-table-column
      prop="parent.name"
      label="父级部门"
      width="100">
    </el-table-column>
    <el-table-column
        prop="path"
        label="部门路径"
        width="100">
    </el-table-column>
    <el-table-column
      label="状态" >
      <template slot-scope="scope">
      <span v-if="scope.row.state!=1" style="color: red">禁用</span>
      <span v-else style="color: green">正常</span>
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button
          size="mini"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    background
    @size-change="handleSizeChange"
    @current-change="currentChangeFunc"
    :current-page="query.currentPage"
    :page-size="query.pageNumber"
    :page-sizes="[10, 20, 50]"
    layout="total, sizes, prev, pager, next, jumper"
    :total=kq.total>
  </el-pagination>
    <!--新增/修改的弹出框   :visible.sync 用来控制弹出框是关闭还是打开的  true 打开  false 关闭 -->
    <el-dialog title="新增/修改" :visible.sync="dialogFormVisible" v-loading="loading">
      <el-form :model="department">
        <el-form-item label="部门" label-width="200">
          <el-input v-model="department.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门领导" label-width="200">
<!--          <el-input v-model="department.head" autocomplete="off"></el-input>-->
          <el-select v-model="department.head" clearable value-key="id" placeholder="请选择">
            <!--下拉选项
              :key=""  //唯一标识
              :label 选择之后展示到选择框中的值
              :value 选中之后绑定给模型层的值  如果要绑定对象给模型层 有一个大坑
                 必须要写  value-key="id"
            -->
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="父级部门" label-width="200">
<!--          <el-input v-model="department.parent.id" autocomplete="off"></el-input>-->
          <el-cascader v-model="department.parent"
                       :options="deptTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="状态" label-width="200">
          <el-radio-group v-model="department.state">
            <el-radio class="radio" :label="1">正常</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门介绍" label-width="200">
          <el-input type="textarea" v-model="department.intro" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      department:{
        id:null,
        name:"",
        intro:"",
        head:{
          id:null
        },
        parent:{
          id:null
        },
        path:"",
        state:null

      },
      kq: {
        data:null,
        total:null
      },
      heart:[],
      employees:[],
      deptTree:[],
      query:{
        currentPage:1,
        pageNumber:10,
        keyword:"",
      },
      dialogFormVisible:false,
      loading:false
    }

  },
  methods:{
    handleSelectionChange(rows){  //获取批量删除的多有id
      this.heart=rows;
      console.log(this.heart)
    },

    handleEdit(index, row) {
      this.dialogFormVisible=true;
      this.department= Object.assign({}, row);
      // 因为head是对象,他为null，不代表他里面的值也为空
      if (this.department.head == null){
        this.department.head={id:null}
      }
      if (row.path !=null){
        let array=row.path.split("/");
        let ary=[];
        for (let i=1;i<array.length-1;i++){
          ary.push(parseInt(array[i]));
        }
        this.department.parent=ary;
      }
      this.getHead();
      this.getDepartmentTree();
    },
    //保存
    save(){
      this.loading = true;  // 弹出加载框
      // 1 判断字段的非空校验
      // 2 发起请求保存数据
      let param = Object.assign({}, this.department);
      //因为我们后端的parent是一个对象,而级联给我们的是一个数组，所以我们要转换一下
      if (param.parent != null){
        let array=param.parent;
        param.parent={id:array[array.length-1]};
      }
      this.$http.put("/department",param)
        .then(result => {
          this.loading = false;
          result = result.data;
          if(result.success){
            this.showMessage(1,"保存成功!");
            this.query.currentPage = 1;
            this.initPageData();
            this.dialogFormVisible = false; // 关闭模态框
          }else{
            this.showMessage(2,"保存失败")
          }
        })
    },

    //获取部门领导
    getHead(){
      this.$http.get("/employee")
                .then(result=>{
                  var data = result.data;
                  this.employees=data.object;
                  if (data.success){
                    // this.showMessage(1,"获取部门领导成功！")
                  }else {
                    this.showMessage(2,"获取部门领导失败！")
                  }
                })
                .catch(result=>{
                this.showMessage(2,"获取部门领导失败！")
      })
    },
    //获取部门树
    getDepartmentTree(){
      this.$http.get("/department/tree")
          .then(result=>{
            var data = result.data;
            this.deptTree=data.object;
            if (data.success){
              // this.showMessage(1,"获取部门领导成功！")
            }else {
              this.showMessage(2,"获取部门领导失败！")
            }
          })
          .catch(result=>{
            this.showMessage(2,"获取部门领导失败！")
          })
    },

    //新增
    showModal(){
      // 新增前先清空上次的操作数据
      this.department={
        id:null,
        name:"",
        intro:"",
        head:{
          id:null
        },
        parent:{
          id:null
        },
        path:"",
        state:null
      }
      //弹出模态框
      this.dialogFormVisible=true;
      this.getHead();
      this.getDepartmentTree();
    },

    //批量删除
    batchDelete(){
      //获取批量删除的所有id
      let ids = this.heart.map(map=>map.id);
      //先判断用户是否勾选了
      if (ids.length<1){
        //小于1就提示用户
        this.showMessage(2,"未选择！");
        return;
      }
      //提示用户是否要删除
      this.$confirm('此操作将永久删除数据, 是否继续?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => { // 如果用户选择确定,就会走then这个方法
        // 4 如果选择确定,就发起删除请求
        console.log(ids)
        this.$http.patch("/department",ids)
          .then(result=>{
            let data=result.data;
            if (data.success){
              this.showMessage(1,"删除成功");
              //删除后刷新数据
              this.query.currentPage=1;
              this.initPageData();
            }
          })
      }).catch(()=>{  //取消就进入这个方法
        this.showMessage(3,"取消成功")
      })
    },

    //删除
    handleDelete(index, row) {
      //获取id
      let id=row.id;
      //提示用户是否删除
      this.$confirm('此操作将永久删除数据, 是否继续?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => { // 如果用户选择确定,就会走then这个方法
        // 4 如果选择确定,就发起删除请求
        this.$http.delete("/department/"+id)
                  .then(result=>{
                    let data=result.data;
                    if (data.success){
                      this.showMessage(1,"删除成功");
                      //删除后刷新数据
                      this.query.currentPage=1;
                      this.initPageData();
                    }
                  })
      }).catch(()=>{  //取消就进入这个方法
          this.showMessage(3,"取消成功")
      })
    },
    showMessage(type,message){
      if(type == 1){
        this.$message({
          type: 'success',
          message: message
        });
      }else if(type == 2){
        this.$message({
          type: 'error',
          message: message
        });
      }else if(type == 3){
        this.$message({
          type: 'info',
          message: message
        });
      }
    },
    currentChangeFunc(val){
      this.query.currentPage=val;
      this.initPageData();
    },
    handleSizeChange(val){
      this.query.pageNumber=val;
      this.query.currentPage = 1;
      this.initPageData();
    },
    initPageData(){
      this.$http.post("/department",this.query)
        .then(result=>{
          this.query.keyword=""
          let pageData = result.data;
         this.kq=pageData.object;
        }).catch(result=>{
          alert(result.message)
      })
    }
  },
  mounted() {
    this.initPageData()
  }
}
</script>
